<?php
/**
 * Author: wl
 * Email: 446399160@qq.com
 * DateTime: 2017/05/01 13:31
 */

namespace app\modules\v1\models;
use yii\db\ActiveRecord;
use app\modules\v1\models\MerchantWeixin;
use app\modules\v1\models\Merchant;
use yii\base\Exception;
use Yii;

class Weixinfocus extends ActiveRecord{
	
	/**
	 * 验证处理
	 */
	public function valid(){
		$echoStr = Yii::$app->request->get('echostr');
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}
	
	/**
	 * 响应处理
	 */
	public function responseMsg(){
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj        = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername   = $postObj->FromUserName;   //接收方帐号（收到的OpenID）
			$toUsername     = $postObj->ToUserName;     //开发者微信号
			$content        = trim($postObj->Content);  //回复的消息内容
			$time           = time();                   //消息创建时间 （整型）
			$Event			= (string)$postObj->Event;
			$EvenKey        = trim((string)$postObj->EventKey);		//事件key值
			$keyarray		= explode("_", $EvenKey);
			$ticket         = $postObj->Ticket;
			if(count($keyarray) == 2){
				//未关注者点击关注
				$scene_str = $keyarray[1];
			}else{
				//已关注者扫描
				$scene_str = $EvenKey;
			}
			
			

			
			
			
			
			$merchantweixin = new MerchantWeixin();
			if($Event == 'subscribe'){ //用户点击关注事件
				$appid			= Yii::$app->params['appid'];
				$appsecret		= Yii::$app->params['appsecret'];
				//获取用户信息：
				$token_url 		= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
				$token_output 	= $this->https_request($token_url);
				$token_info 	= json_decode($token_output);
				$access_token 	= $token_info->access_token;
				$userinfo 		= $this->getInfo($access_token, $fromUsername);
				$weixin_pic		= isset($userinfo->headimgurl)?$userinfo->headimgurl:'';
				$weixin_openid	= isset($userinfo->openid)?$userinfo->openid:$fromUsername;
				$weixin_nick	= isset($userinfo->nickname)?$userinfo->nickname:'';
				$weixin_sex		= isset($userinfo->sex)?$userinfo->sex:0;
				$weixin_city	= isset($userinfo->city)?$userinfo->city:'';
				$weixin_province= isset($userinfo->province)?$userinfo->province:'';
				$weixin_country	= isset($userinfo->country)?$userinfo->country:'';
				$weixin_subscribe_time 	= isset($userinfo->subscribe_time)?date('Y-m-d H:i:s',$userinfo->subscribe_time):date('Y-m-d H:i:s'); //关注时间
				$weixin_remark	= isset($userinfo->remark)?$userinfo->remark:'';
				$weixin_groupid	= isset($userinfo->groupid)?$userinfo->groupid:0;
				//保存到数据库
				$weixininfo 	= $merchantweixin->findByOpenid($weixin_openid);
				if(empty($weixininfo)){
					//查询最大id
					$maxid  	= Merchant::find()->max('id')+1;
					$db 		= Yii::$app->db;
					$transaction= $db->beginTransaction();  //开启事务
					try {
						$query1 = "insert into merchant (id,merchant_name,head_img,source,check_status,wx_nickname)
            					value ('{$maxid}','{$weixin_nick}','{$weixin_pic}',4,0,'{$weixin_nick}') ";
						
						$query2 = "insert into merchant_weixin (merchant_id,openid,nickname,sex,headimg,city,
								province,country,subscribe_time,remark,groupid,status,scene_str)
								value ({$maxid},'{$weixin_openid}','{$weixin_nick}',{$weixin_sex},'{$weixin_pic}',
								'{$weixin_city}','{$weixin_province}','{$weixin_country}','{$weixin_subscribe_time}',
								'{$weixin_remark}','{$weixin_groupid}',1,'{$scene_str}')";
						$transaction->createCommand($query1)->execute();
						$transaction->createCommand($query2)->execute();
						$transaction->commit();
					} catch (Exception $e) {
						$transaction->rollBack();
					}
				}else{
					if($weixininfo->status == 0){
						$weixininfo->status = 1;
					}
					if($weixininfo->scene_str != $scene_str){
						$weixininfo->scene_str  = $scene_str;
					}
					$subscribe_time = date('Y-m-d H:i:s');
					$weixininfo->subscribe_time = $subscribe_time;
					$weixininfo->update();
				}
				$textTpl   = "<xml>
								<ToUserName><![CDATA[%s]]></ToUserName>
								<FromUserName><![CDATA[%s]]></FromUserName>
								<CreateTime>%s</CreateTime>
								<MsgType><![CDATA[news]]></MsgType>
								<ArticleCount>1</ArticleCount>
								<Articles>
								<item>
								<Title><![CDATA[收款小工具]]></Title>
		                    	<Description><![CDATA[商家收款小工具最新版本！]]></Description>
		                    	<PicUrl><![CDATA[https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1145532481,1147318895&fm=23&gp=0.jpg]]></PicUrl>
		                    	<Url><![CDATA[http://211.149.198.73/php/introduce.html]]></Url>
		                    	</item>
		                    	</Articles>
		                    </xml>";
                $resultStr  = sprintf($textTpl, $fromUsername, $toUsername, $time);
                echo $resultStr;
                exit;
            }
            if($Event == 'unsubscribe'){ //用户取消关注事件
            	//更新数据库
            	$weixininfo 	= $merchantweixin->findByOpenid($fromUsername);
            	$subscribe_time = date('Y-m-d H:i:s');
            	$weixininfo->subscribe_time = $subscribe_time;
            	$weixininfo->status			= 0;
            	$weixininfo->update();
            	
            	
            }
            
		}else{
			$textTpl2   = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
			$msgType    	= "text";
			$contentStr 	= "欢迎使用信用付！";
			$resultStr  	= sprintf($textTpl2, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
            exit;
        }
    }
	
	/**
	 * 微信签名认证
	 * @return boolean
	 */
    private function checkSignature(){
        $signature 	= Yii::$app->request->get('signature');
        $timestamp 	= Yii::$app->request->get('timestamp');
        $nonce 		= Yii::$app->request->get('nonce');
        $token 		= Yii::$app->params['token'];
        $tmpArr 	= array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr 	= implode( $tmpArr );
		$tmpStr 	= sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	* 根据用户openid获取用户基本信息
	* @param 微信公众号token  $access_token
	* @param 微信用户openid  $openid
	* @return userinfo 对象
	*/
	private function getInfo($access_token,$openid){
    	$url 		= "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
	    $output 	= $this->https_request($url);
		$userinfo 	= json_decode($output);
		return $userinfo;
	}
	
	/**
	* curl请求数据
	* @param 地址     $url
	* @return string|mixed
	*/
	private function https_request($url,$data = ''){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		if(!empty($data)){
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		 $data = curl_exec($curl);
		 if (curl_errno($curl)) {
		 return 'ERROR '.curl_error($curl);}
		 curl_close($curl);
		 return $data;
	}
	
	
}